import {Component, OnInit} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {Location} from "@angular/common";
import {NewsService} from "../news.service";

@Component({
  selector: 'app-news-edit',
  templateUrl: './news-edit.component.html',
  styleUrls: ['./news-edit.component.css']
})
export class NewsEditComponent implements OnInit {
  public isConfirmLoading: boolean = false;
  public code: string; //news
  public validateForm: FormGroup;//企业登录的表单

  constructor(private fb: FormBuilder, private newsService: NewsService, private route: ActivatedRoute, public location: Location) {
    this.validateForm = this.fb.group({
      title: [null, Validators.compose([Validators.required,Validators.maxLength(64)])], // 公告标题 64个汉字
      content: [null, Validators.compose([Validators.required])], // 摘要 256个汉字
    });
  }

  ngOnInit() {
    this.route.url.subscribe(url => {
      const curPath = url[0].path;
      if (curPath === 'modify') {
        this.code = this.route.snapshot.params.code;//获取参数
        this.loadNewsInfo();
      }//修改前查询出供应商信息
    })
  }

  /**
   * 表单确认
   */
  addNews($event) {
    $event.preventDefault();
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isConfirmLoading = true;
    let formData = Object.assign({},this.validateForm.value);
    //添加news
    if (this.code) {
      formData.code = this.code;
      this.newsService.modifyNews(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.location.back();
      }).catch(res => this.isConfirmLoading = false)
    } else {
      this.newsService.addNews(formData).then((data: any) => {
        this.isConfirmLoading = false;
        this.location.back();
      }).catch(res => this.isConfirmLoading = false)
    }
  }

  /**
   * 查询news信息
   */
  loadNewsInfo() {
    this.newsService.loadNewsByCode(this.code).then((data: any) => {
      let news = {
        title: data.title,
        content: data.newsContent.content
      };
      this.validateForm.patchValue(news);
    })
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}
